package com.web.hr.Utils;

import org.apache.log4j.Logger;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;

/**
 * @Author：LJ
 * @Description：
 * @Date: 2017/9/3
 * @Modified By:
 */
public class FileUtil {
    static Logger logger = Logger.getLogger(FileUtil.class);
    private static String ENCODING = "UTF-8";

    /**
     * 从输入流中获取字节数组
     *
     * @param inputStream
     * @return
     * @throws IOException
     */
    public static byte[] readInputStream(InputStream inputStream) throws IOException {
        byte[] buffer = new byte[1024];
        int len;
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        while ((len = inputStream.read(buffer)) != -1) {
            bos.write(buffer, 0, len);
        }
        bos.close();
        return bos.toByteArray();
    }

    /**
     * FiletUtil.downloadFileFromNet
     * 从网络中下载文件
     */
    public static void downloadFileFromNet(String urlPath, String fileName, HttpServletResponse response) throws MalformedURLException {
        InputStream fis = null;
        OutputStream os = null;
        try {
            URL url = new URL(urlPath);
            logger.info("-U " + urlPath);
            URLConnection urlConnection = url.openConnection();
            // 以流的形式下载文件
            fis = new BufferedInputStream(urlConnection.getInputStream());
            // 设置响应报头
            response.reset();
            response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, ENCODING));
            response.setCharacterEncoding(ENCODING);
            //获取自己数组
            byte[] getData = readInputStream(fis);
            os = new BufferedOutputStream(response.getOutputStream());
            os.write(getData);
        } catch (Throwable e) {
            e.printStackTrace();
        } finally {
            try {
                if (os != null) {
                    os.close();
                }
                if (fis != null) {
                    fis.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 在本机服务器上下载文件
     */
    public static void downloadFile(HttpServletResponse response, String fileName, String realPath) throws UnsupportedEncodingException {
        File file = new File(realPath, fileName);
        InputStream fis = null;
        OutputStream os = null;
        try {
            if (!file.exists()) {
                response.getWriter().print("文件不存在");
            }
            // 以流的形式下载文件
            fis = new BufferedInputStream(new FileInputStream(file));
            // 设置响应报头
            response.reset();
            response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(file.getName(), ENCODING));
            response.addHeader("Content-Length", "" + file.length());
            //response.setContentType(MIME_TYPE_BIN);
            response.setCharacterEncoding(ENCODING);

            // 写入响应流数据
            os = new BufferedOutputStream(response.getOutputStream());
            byte[] bytes = new byte[1024];
            while (fis.read(bytes) != -1) {
                os.write(bytes);
            }
        } catch (Throwable e) {
            e.printStackTrace();
        } finally {
            try {
                if (os != null) {
                    os.close();
                }
                if (fis != null) {
                    fis.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
